import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/index.vue'

import utils from '@/utils'

// 重写路由push方法
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to){
  return VueRouterPush.call(this,to).catch(err=>err)
}

Vue.use(VueRouter)

const routes = [
  // 配置路由映射关系
  {
    path:'/',
    // 重定向到 /login页面
    redirect:'/login'
  },
  {
    path:'/login',
    component:()=>import('@/views/Login/index.vue')
  },
  {
    path:'/sign',
    component:()=>import('@/views/Sign/index.vue')
  },
  {
    path:'/main',
    component:()=>import('@/views/Main/index.vue'),
    redirect:'/main/home',
    // 配置子路由
    children:[
      {
        path:'home',
        component:()=>import('@/views/Home/index.vue')
      },
      {
        path:'order',
        component:()=>import('@/views/Order/index.vue')
      },
      {
        path:'help',
        component:()=>import('@/views/Help/index.vue')
      },
      {
        path:'my',
        component:()=>import('@/views/My/index.vue')
      },
      {
        path:'product/:productId',
        component:()=>import('@/views/Detail/index.vue')
      },
      {
        path:'address',
        component:()=>import('@/views/Address/index.vue')
      },
      {
        path:'helpDetail/:id',
        component:()=>import('@/views/HelpDeil/index.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 添加路由守卫，确保用户只有在完成登录之后才能看到首页
router.beforeEach((to,from,next)=>{
  let isAuth;
  let istk = utils.getToken('tk')
  if(istk!= undefined){
    isAuth = true
  }else{
    isAuth = false
  }
  // 用户在未登录的状态下可以前往 登录和注册页面
  if(to.path == '/login' || to.path == '/sign'){
    next()
  }else{
    if(isAuth){
      next()
    }else{
      utils.showMessage('danger','您还未登录')
      router.push('/login')
    }
  }
})

export default router
